﻿using System;
using System.Linq;
using System.Collections.Generic;
using System.Text;
using Silvermoon.Controls;
using OutlookHub.Utils;
using Silvermoon.OpenGL;
using System.Drawing;
using Silvermoon.Shapes;
using Silvermoon.UI;
using Silvermoon.Windows.Styles;
using Silvermoon.Utils;
using Silvermoon.Windows;
using OutlookHub.Models;
using Silvermoon.Navigation;
using OutlookHub.Styles;
using OutlookHub.Controllers;
using OutlookHub.Classes;
using MAPIdotnet;
using System.Threading;

namespace OutlookHub.Pages
{
    public class OutlookPanorama : Page
    {
        private Panorama hub;
        private PanoramaSection all, today;
        private OutlookController controller;
        private TitleCountItem eMailBtn;
        private TitleCountItem tasksBtn;
        private ListView accountsListView;
        private ListViewController<TitleCountItem, Store> accountsController;

        public OutlookPanorama()
            : base()
        {
            Initialize();
        }


        public EMailContext Context
        {
            get { return EMailContext.Context; }
        }

        private void Initialize()
        {
            KeepAlive = true;
            controller = new OutlookController();
            Styles = StylePool.Outlook;

            hub = new Panorama { Margin = Margin.Zero, Title = "Outlook", TitleFontScale = 1.0f, TitleFont = FontPool.HubFont };
            hub.Background = new GradientShape { StartColor = PhoneColors.FromRgb(249, 226, 127), EndColor = PhoneColors.White, Orientation = ColorOrientation.TopLeft };
            hub.TitleColor = PhoneColors.FromRgb(227, 120, 20);
            hub.TextColor = PhoneColors.MediumDark;
            this.Styles.SetClass(typeof(Button), new ButtonStyle { Padding = Margin.Empty, Font = FontPool.MediumRegularFont, Background = Shape.Empty, TextColor = PhoneColors.Black });


            all = CreateSection("");
            today = CreateSection("accounts");
            hub.Sections.Add(all);
            hub.Sections.Add(today);

            InitializeAll(all);
            InitializeAccounts(today);

            Controls.Add(hub);
        }

        private void InitializeAccounts(PanoramaSection accountsSection)
        {

            ListView lv = new ListView { Margin = new Margin(24, 80, 10, 0) };
            accountsListView=lv;
            lv.KeepItems = true;
            ListViewController<TitleCountItem, Store> controller = new ListViewController<TitleCountItem, Store>(lv) { ItemHeight = 80 };
            accountsController=controller;
            controller.UpdateItem += new EventHandler<ItemControlGeneratorEventArgs<TitleCountItem>>(controller_UpdateItem);
            lv.TapItem += new EventHandler<ItemEventArgs>(OnAccountItemTap);

            accountsSection.Controls.Add(lv);

            EMailContext context = Context;
            controller.DataSource = context.Stores;

        }

        void OnAccountItemTap(object sender, ItemEventArgs e)
        {
            Item item = e.Item;
            Store store = item.DataValue as Store;
            Context.CurrentStore = store;
            OpenEmails();

        }

        void controller_UpdateItem(object sender, ItemControlGeneratorEventArgs<TitleCountItem> e)
        {
            Store store = e.Value as Store;
            TitleCountItem item = e.Item;
            item.Text = store.Name;

            EnqueueThread(() =>
                {
                    if (EMailContext.Context != null)
                    {
                        int n = store.UnreadMessagesCount;
                        item.Invoke(() => item.Count = n);
                    }
                });
        }


        private void InitializeAll(PanoramaSection contacts)
        {
            Button contactBtn = new Button { Bounds = new Rectangle(24, 80 + 0 * 80, 320, 80), Content = "Contacts" };
            eMailBtn = new TitleCountItem { Bounds = new Rectangle(24, 80 + 1 * 80, 320, 80), Text = "eMails" };

            tasksBtn = new TitleCountItem { Bounds = new Rectangle(24, 80 + 2 * 80, 320, 80), Text = "Tasks" };
            Button calendarBtn = new Button { Bounds = new Rectangle(24, 80 + 3 * 80, 320, 80), Enabled = true, Content = "Calendar" };

            tasksBtn.Tap += new EventHandler<TapEventArgs>(OnOpenTasks);
            contactBtn.Tap += (s, e) => OpenContacts(false);
            eMailBtn.Tap += new EventHandler<TapEventArgs>(OnOpenEmails);
            calendarBtn.Tap += (s, e) => OpenCalendar();
            contacts.Controls.Add(contactBtn, eMailBtn, tasksBtn, calendarBtn);
        }

        void OnOpenTasks(object sender, TapEventArgs e)
        {
            Page calendar = new TasksPage();
            this.NavigateTo(calendar);
        }

        void OnOpenEmails(object sender, EventArgs e)
        {
            Context.CurrentStore = Context.DefaultEMailStore;

            OpenEmails();
        }

        private void OpenEmails()
        {
            EMailsPage page = new EMailsPage();
            this.NavigateTo(page);
        }


        private void OpenCalendar()
        {
            CalendarPage calendar = new CalendarPage();
            this.NavigateTo(calendar);
        }


        private void OpenContacts(bool styled)
        {
            ContactPage contacts = new ContactPage { Styled = styled };
            this.NavigateTo(contacts);
        }


        private PanoramaSection CreateSection(string title)
        {
            PanoramaSection section = new PanoramaSection { Margin = Margin.Zero };
            Label titleLabel = new Label
            {
                AutoSize = true,
                Font = FontPool.BigRegularFont,
                Alignment = Alignment.Near,
                LineAlignment = Alignment.Near,
                Text = title
            };
            section.Controls.Add(titleLabel);

            return section;
        }

        protected override void OnShown()
        {
            Invoke(() => EnqueueThread(DetermineItemCounts));
            accountsListView.UpdateItems();
            base.OnShown();
        }

        private void DetermineItemCounts()
        {
            if (EMailContext.Context != null)
            {
                Store store = Context.DefaultEMailStore;
                int n = store.UnreadMessagesCount;
                eMailBtn.Invoke(() => eMailBtn.Count = n);
            }
            Thread.Sleep(0);
            var ct = OutlookContext.Context;
            if (ct != null)
            {
                int n = ct.TodayTasks.Count();
                tasksBtn.Invoke(() => tasksBtn.Count = n);
            }
        }


        class ViewStateBag
        {
            public int HubOffset;
        }

        public override object OnSaveViewState()
        {
            return new ViewStateBag { HubOffset = hub.Offset };
        }

        public override void OnLoadViewState(object viewState)
        {
            ViewStateBag bag = viewState as ViewStateBag;
            if (bag != null)
            {
                hub.Offset = bag.HubOffset;
            }
        }
    }
}